package com.slipper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.slipper.system.api.dictionary.service.IDictionarySv;

@Component
public class PaasContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        PaasContext.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return PaasContext.applicationContext.getBean(clazz);
    }

    public static <T> Map<String, T> getBeans(Class<T> clazz) {
        return PaasContext.applicationContext.getBeansOfType(clazz);
    }

    public static Object getBean(String beanName) {
        return PaasContext.applicationContext.getBean(beanName);
    }

    public static Map<String, Map<String, String>> getDicMap(String...dicCodes) {
        return getDicMap(false, dicCodes);
    }

    /**
     * 获取字典，以key, value形式返回
     * @param reverse，是否将key, value反转保存
     */
    public static Map<String, Map<String, String>> getDicMap(boolean reverse, String...dicCodes) {
        IDictionarySv dictionarySv = PaasContext.getBean(IDictionarySv.class);
        Map<String, Map<String, String>> result = new HashMap<>();
        for (String dicCode : dicCodes) {
            Map<String, String> dicData = dictionarySv.querySingleDicData(dicCode).getData();
            if (reverse) {
                Map<String, String> newDicData = new HashMap<>();
                for (Map.Entry<String, String> entry : dicData.entrySet()) {
                    newDicData.put(entry.getValue(), entry.getKey());
                }
                dicData = newDicData;
            }
            result.put(dicCode, dicData);
        }
        return result;
    }

    /**
     *
     * @param key id 不为空
     * @param value name 不为空
     */
    public static <T> Map<String, Map<String, String>> putDataToDicMap(Map<String, Map<String, String>> dicMap, List<T> dataList,String key,String value,String dicKey) {
        if (!dataList.isEmpty()) {
            Map<String,String> dic = new HashMap<>();
            for (T t: dataList) {
                BeanWrapper beanWrapper = new BeanWrapperImpl(t);
                dic.put(Objects.requireNonNull(beanWrapper.getPropertyValue(value)).toString(),
                        Objects.requireNonNull(beanWrapper.getPropertyValue(key)).toString());
            }
            dicMap.put(dicKey,dic);
        }
        return dicMap;
    }
}
